const gulp = require('gulp')
const del = require('del')
const path = require('path')
const autoprefixer = require('gulp-autoprefixer')
const htmlmin = require('gulp-htmlmin')
const sass = require('gulp-sass')
const jsonminify = require('gulp-jsonminify2')
const gutil = require('gulp-util')
const combiner = require('stream-combiner2');
const babel = require('gulp-babel')
const uglify = require('gulp-uglify')
const rename = require("gulp-rename")
const minifycss = require('gulp-minify-css')
const runSequence = require('run-sequence')
const jsonlint = require("gulp-jsonlint")
const plumber = require('gulp-plumber');
const gulpLoadPlugins = require('gulp-load-plugins')
const replace = require('gulp-replace');

// load all gulp plugins
const plugins = gulpLoadPlugins()
const env = process.env.NODE_ENV || 'development'
//const isProduction = () => env === 'production'
const isProduction = 'production'

var colors = gutil.colors;
const handleError = function (err) {
  console.log('\n')
  gutil.log(colors.red('Error!'))
  gutil.log('fileName: ' + colors.red(err.fileName))
  gutil.log('lineNumber: ' + colors.red(err.lineNumber))
  gutil.log('message: ' + err.message)
  gutil.log('plugin: ' + colors.yellow(err.plugin))
};


/**
 * Clean distribution directory
 */
gulp.task('clean', del.bind(null, ['dist/*']))

// gulp.task('clean', () => {
//   return del(['./dist/**'])
// })

gulp.task('watch', () => {
  gulp.watch('src/**/*.js', ['compile:js'])
  gulp.watch('src/**/*.less', ['compile:less'])
  gulp.watch('src/**/*.wxss', ['compile:wxss'])
  gulp.watch('src/**/*.json', ['compile:json'])
  gulp.watch('src/**/*.wxml', ['compile:wxml'])
});


gulp.task('compile:wxss', () => {
  return gulp.src(['src/**/*.wxss'])
    .pipe(plumber(handleError))
    .pipe(plugins.newer('dist'))
    .pipe(minifycss())  
  //   .pipe(cssmin({
  //     advanced: false,//类型：Boolean 默认：true [是否开启高级优化（合并选择器等）]
  //     //keepBreaks: true,//类型：Boolean 默认：false [是否保留换行]
  //     keepSpecialComments: '*'
  // }))
    

    .pipe(plugins.if(isProduction, plugins.cssnano({
      compatibility: '*'
    })))
    .pipe(gulp.dest('dist'))
})

gulp.task('compile:less', () => {
  return gulp.src(['src/**/*.less'])
    .pipe(plumber(handleError))
    .pipe(plugins.less())
    .pipe(plugins.rename({
      extname: '.wxss'
    }))    
    .pipe(plugins.newer('dist'))
    .pipe(plugins.if(isProduction, plugins.cssnano({
      compatibility: '*'
    })))
    //.pipe(minifycss())
    .pipe(gulp.dest('dist'))
})

/**
 * Compile json source to distribution directory
 */
gulp.task('compile:json', () => {
  return gulp.src(['src/**/*.json'])
    .pipe(plumber(handleError))
    .pipe(plugins.newer('dist'))
    // .pipe(plugins.logger({
    //   showChange: true
    // }))
    .pipe(plugins.jsonminify())
    .pipe(gulp.dest('dist'))
})


/**
 * Compile js source to distribution directory
 */
gulp.task('compile:js', () => {
  return gulp.src(['src/**/*.js'])
    .pipe(plumber(handleError))
    .pipe(plugins.newer('dist'))
    //.pipe(plugins.logger({showChange: true}))
    // .pipe(plugins.babel({
    //   presets: ['es2015']
    // }))

    //.pipe(uglify({ mangle: false }))
    //.pipe(plugins.if(isProduction, plugins.uglify()))
    .pipe(babel())
    //.pipe(plugins.uglify())
    .pipe(gulp.dest('dist'))
})

/**
 * Compile wxml source to distribution directory
 */
gulp.task('compile:wxml', () => {
  return gulp.src(['src/**/*.wxml'])
    .pipe(plumber(handleError))
    .pipe(plugins.newer('dist'))
    .pipe(plugins.if(isProduction, plugins.htmlmin({
      minifyJS: true,
      minifyCSS: true,
      collapseWhitespace: true,
      keepClosingSlash: true,
      removeComments: true,
      removeEmptyAttributes: true,
      removeScriptTypeAttributes: true,
      removeStyleLinkTypeAttributes: true
    })))

    // 删除换行符和tab缩进
    .pipe(replace(/\n+|\t+/g, ''))
    // 将连续空格替换为单个空格
    .pipe(replace(/\s+/g, ' '))
    // 将" <"和"> "的空格删除
    .pipe(replace(/(>\s)/g, '>'))
    .pipe(replace(/(\s<)/g, '<'))
    // 删除注释
    .pipe(replace(/<!--[\w\W\r\n]*?-->/g, ''))

    .pipe(gulp.dest('dist'))
})



/**
 * Compile img source to distribution directory
 */
gulp.task('compile:img', () => {
  return gulp.src(['src/**/*.{jpg,jpeg,png,gif}'])
    .pipe(plumber(handleError))
    .pipe(plugins.newer('dist'))
    .pipe(plugins.imagemin())
    .pipe(gulp.dest('dist'))
})

/**
 * Copy extras to distribution directory
 */
gulp.task('extras', [], () => {
  return gulp.src([
      'src/**/*.*',
      '!src/**/*.rar',
      '!src/**/*.ts',
      '!src/**/*.less',
      '!src/**/*.wxss',
      '!src/**/*.json',
      '!src/**/*.{jpe?g,png,gif}'
    ])
    .pipe(gulp.dest('dist'))
})

/**
 * Compile source to distribution directory
 */
// gulp.task('compile', ['clean'], next => {
//   runSequence([
//       'compile:js',
//       'compile:wxml',
//       'compile:less',
//       'compile:wxss',
//       'compile:json',
//       'compile:img'
//   ], next)
// })

gulp.task('compile', ['clean'], next => {
  runSequence([
    'compile:js',
    'compile:wxml',
    'compile:less',
    'compile:wxss',
    'compile:json',
    'compile:img'
  ], next)
})



/**
 * Build
 */
gulp.task('build', next => runSequence(['compile'], next))

/**
 * Watch source change
 */
gulp.task('watch', ['build'], () => {
  gulp.watch('src/**/*.js', ['compile:js'])
  gulp.watch('src/**/*.wxml', ['compile:wxml'])
  gulp.watch('src/**/*.less', ['compile:less'])
  gulp.watch('src/**/*.wxss', ['compile:wxss'])
  gulp.watch('src/**/*.json', ['compile:json'])
  gulp.watch('src/**/*.{jpe?g,png,gif}', ['compile:img'])
})